package cn.xspace.wnx.view.chat.chatrow;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.xspace.android.xafcommon.been.BaseReturnBean;
import com.xspace.android.xafcommon.util.Constants;
import com.xspace.android.xafcommon.util.DateUtils;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.view.RoundAngleImageView;
import com.xspace.android.xafview.imgview.image.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import cn.xspace.chatui.bean.ChatFileEntity;
import cn.xspace.chatui.bean.MessageEntity;
import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.library.util.OkHttpManager;
import cn.xspace.wnx.R;
import cn.xspace.wnx.activity.ChatActivity;
import cn.xspace.wnx.db.ChatFileDao;
import cn.xspace.wnx.db.ChatRecordDao;
import cn.xspace.wnx.db.MessageRecordDao;
import cn.xspace.wnx.view.chat.ChatMessageList;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;


public abstract class BaseChatRow extends LinearLayout {
    protected static final String TAG = BaseChatRow.class.getSimpleName();

    protected LayoutInflater inflater;
    protected Context context;
    protected BaseAdapter adapter;
    protected MsgRecordEntity message;
    protected int position;
    /**
     * 时间戳
     */
    protected TextView timeStampView;
    /**
     * 显示头像
     */
    protected ImageView userAvatarView;
    /**
     * 泡泡
     */
    protected View bubbleLayout;
    /**
     * 用户昵称
     */
    protected TextView usernickView;
    protected String localKeyId = "";
//    protected TextView percentageView;
    /**
     * 进度条
     */
    protected ProgressBar progressBar;
    /**
     * 是否发送成功标识
     */
    protected ImageView statusView;
    protected Activity activity;

//    protected TextView ackedView;
//    protected TextView deliveredView;
    /**
     * 本人头像
     */
    protected String userLogo;
    protected int chatType = MsgType.CHAT_SINGLE.toNumber();


    //    protected EMCallBack messageSendCallback;
//    protected EMCallBack messageReceiveCallback;
    protected String userId = "";
    protected Map<String, Object> sendMap;
    protected ChatMessageList.MessageListItemClickListener itemClickListener;

    private final CompositeSubscription mAllSubscription = new CompositeSubscription();

    public BaseChatRow(Context context, MsgRecordEntity message, int position, BaseAdapter adapter) {
        super(context);
        if (message.msg_type == MsgType.CHAT_SINGLE.toNumber()) {
            localKeyId = message.msg_sender_id;
        } else if (message.msg_type == MsgType.CHAT_CROUP.toNumber()) {
            localKeyId = message.msg_group_id;
        }else if (message.msg_type == MsgType.CHAT_QAC_FORM.toNumber()){
            localKeyId = message.msg_sender_id;
        }

        userId = MyInfoUtil.getMyUserid(context);
        this.context = context;
        this.message = message;
//        userId = MyInfoUtil.getMyUserid(context);

        userLogo = MyInfoUtil.getMyLogo(context);
        LogUtil.d(TAG, "userLogo>>>>>>" + userLogo);
        this.activity = (Activity) context;
        this.position = position;
        this.adapter = adapter;
        inflater = LayoutInflater.from(context);
        initView();
    }

    protected void registerSubscription(Subscription subscription) {
        mAllSubscription.add(subscription);
    }

    protected void unregisterSubscription(Subscription subscription) {
        mAllSubscription.remove(subscription);
    }

    protected void clearSubscription() {
        mAllSubscription.clear();
    }


    protected ImageLoader.ImageLoaderCallback logoLoadCallback = new ImageLoader.ImageLoaderCallback() {
        @Override
        public void onImageLoadingStarted(ImageLoader loader) {

        }

        @Override
        public void onImageLoadingEnded(ImageLoader loader, Bitmap bitmap) {
            userAvatarView.setImageResource(R.drawable.icon_header_default);
        }

        @Override
        public void onImageLoadingFailed(ImageLoader loader, Throwable exception) {
            userAvatarView.setImageResource(R.drawable.icon_header_default);
        }
    };

    /**
     * 判断是否是我发的
     *
     * @return
     */
    protected boolean isMySend() {
        if ("1".equals(message.is_mine)) {
            return true;
        }
        return false;
//        if (userId != null && userId.equals(message.msg_sender_id)) {
//            return true;
//        } else {
//            return false;
//        }
    }

    protected void initView() {
        onInflateView();
        timeStampView = (TextView) findViewById(R.id.timestamp);
        userAvatarView = (RoundAngleImageView) findViewById(R.id.iv_userhead);
        bubbleLayout = findViewById(R.id.bubble);
        usernickView = (TextView) findViewById(R.id.tv_userid);

        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        statusView = (ImageView) findViewById(R.id.msg_status);
//        ackedView = (TextView) findViewById(R.id.tv_ack);
//        deliveredView = (TextView) findViewById(R.id.tv_delivered);
        onFindViewById();
    }


    /**
     * set property according message and postion
     *
     * @param message
     * @param position
     */
    public void setUpView(MsgRecordEntity message, int position,
                          ChatMessageList.MessageListItemClickListener itemClickListener) {
        this.message = message;
        this.position = position;
        this.itemClickListener = itemClickListener;

        setUpBaseView();
        onSetUpView();
        setClickListener();
    }

    private boolean isShowTimeIfNeed(MessageEntity msg, MessageEntity previousMsg) {
        long chatTime = 0;
        try {
            chatTime = DateUtils.stringToDate(msg.msg_last_time, null).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        long previousChatTime = 0;
        if (previousMsg != null) {
            try {
                previousChatTime = DateUtils.stringToDate(
                        previousMsg.msg_last_time, null).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        return (chatTime - previousChatTime > 5 * 60 * 1000);// 超过五分钟显示聊天时间
    }


    private void setUpBaseView() {
        // set nickname, avatar and background of bubble
        TextView timestamp = (TextView) findViewById(R.id.timestamp);
        if (timestamp != null) {
            if (position == 0) {
                timestamp.setText(DateUtils.getChatDatetimeDesc(message.msg_last_time));
                timestamp.setVisibility(View.VISIBLE);
            } else {
                // show time stamp if interval with last message is > 30 seconds
                MessageEntity prevMessage = (MessageEntity) adapter.getItem(position - 1);


//                if (prevMessage != null && DateUtils.isCloseEnough(message.msg_last_time, prevMessage.msg_last_time)) {
                if (prevMessage != null && !isShowTimeIfNeed(message, prevMessage)) {
                    timestamp.setVisibility(View.GONE);
                } else {
                    timestamp.setText(DateUtils.getChatDatetimeDesc(message.msg_last_time));
                    timestamp.setVisibility(View.VISIBLE);
                }
            }
        }

        if (userAvatarView != null) {
            //set nickname and avatar
            if (isMySend()) {
                //我发送的，不显示名称
                LogUtil.d(TAG, "userLogo>>>" + userLogo);
                if (!TextUtils.isEmpty(userLogo)) {
                    LogUtil.d(TAG, "userLogok 开始加载");
                    Picasso.with(context)
                            .load(userLogo)
                            .placeholder(R.drawable.icon_header_default)
                            .error(R.drawable.icon_header_default)
                            .into(userAvatarView);
                } else {
                    userAvatarView.setImageResource(R.drawable.icon_header_default);
                }
            } else {
                usernickView.setText(message.msg_sender_name);
                if (!TextUtils.isEmpty(message.msg_logo)) {
                    Picasso.with(context)
                            .load(message.msg_logo)
//                        .resize(R.dimen.chat_header_icon_width, R.dimen.chat_header_icon_height)
                            .placeholder(R.drawable.icon_header_default)
//                        .centerCrop()
                            .error(R.drawable.icon_header_default)
                            .into(userAvatarView);
                } else {
                    userAvatarView.setImageResource(R.drawable.icon_header_default);
                }
            }
        }

    }

    /**
     * set callback for sending message
     */
    protected void setMessageSendCallback() {
        sendMessageByHttp();
//            mCallback = new OkHttpManager.DataCallBack() {
//                @Override
//                public void requestFailure(Request request, IOException e) {
//                    LogUtil.d(TAG, "requestFailure");
//                    message.msg_send_status = MessageEntity.MsgSendStatus.FAILED.toNumber();
//                    updateView();
//                }
//
//                @Override
//                public void requestSuccess(String result) throws Exception {
//                    LogUtil.d(TAG, "requestSuccess" + result);
//                    message.msg_send_status = MessageEntity.MsgSendStatus.SUCCESS.toNumber();
//                    updateView();
//                }
//            };
//            message.setStatusCallback(mCallback);
//            mCallback = new EMCallBack() {
//
//                @Override
//                public void onSuccess() {
//                    updateView();
//                }
//
//                @Override
//                public void onProgress(final int progress, String status) {
//                    activity.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (percentageView != null)
//                                percentageView.setText(progress + "%");
//
//                        }
//                    });
//                }
//
//                @Override
//                public void onError(int code, String error) {
//                    updateView();
//                }
//            };
    }
//        if (messageSendCallback == null) {
//            messageSendCallback = new EMCallBack() {
//
//                @Override
//                public void onSuccess() {
//                    updateView();
//                }
//
//                @Override
//                public void onProgress(final int progress, String status) {
//                    activity.runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (percentageView != null)
//                                percentageView.setText(progress + "%");
//
//                        }
//                    });
//                }
//
//                @Override
//                public void onError(int code, String error) {
//                    updateView();
//                }
//            };
//        }
//        message.setMessageStatusCallback(messageSendCallback);

    /**
     * set callback for receiving message
     */
    protected void setMessageReceiveCallback() {
//        if (messageReceiveCallback == null) {
//            messageReceiveCallback = new EMCallBack() {
//
//                @Override
//                public void onSuccess() {
//                    updateView();
//                }
//
//                @Override
//                public void onProgress(final int progress, String status) {
//                    activity.runOnUiThread(new Runnable() {
//                        public void run() {
//                            if (percentageView != null) {
//                                percentageView.setText(progress + "%");
//                            }
//                        }
//                    });
//                }
//
//                @Override
//                public void onError(int code, String error) {
//                    updateView();
//                }
//            };
//        }
//        message.setMessageStatusCallback(messageReceiveCallback);
    }


    protected void setClickListener() {
        if (bubbleLayout != null) {
            bubbleLayout.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    LogUtil.d(TAG, "bubbleLayout.setOnClickListener " + (itemClickListener == null));
                    if (itemClickListener != null) {
                        if (!itemClickListener.onBubbleClick(message)) {
                            // if listener return false, we call default handling
                            onBubbleClick();
                        }
                    }
                }
            });

            bubbleLayout.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    LogUtil.d(TAG, "bubbleLayout.setOnClickListener");
                    if (itemClickListener != null) {
                        itemClickListener.onBubbleLongClick(message);
                    }
                    return true;
                }
            });
        }

        if (statusView != null) {
            statusView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        itemClickListener.onResendClick(message);
                    }
                }
            });
        }

        if (userAvatarView != null) {
            userAvatarView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (itemClickListener != null) {
                        if (isMySend()) {
                            itemClickListener.onUserAvatarClick(userId);
                        } else {
                            itemClickListener.onUserAvatarClick(message.msg_sender_id);
                        }
                    }
                }
            });
            userAvatarView.setOnLongClickListener(new OnLongClickListener() {

                @Override
                public boolean onLongClick(View v) {
                    if (itemClickListener != null) {
//                        if (message.direct() == Direct.SEND) {
//                            itemClickListener.onUserAvatarLongClick(EMClient.getInstance().getCurrentUser());
//                        } else {
//                            itemClickListener.onUserAvatarLongClick(message.getFrom());
//                        }
                        return true;
                    }
                    return false;
                }
            });
        }
    }


    protected void updateView() {
        activity.runOnUiThread(new Runnable() {
            public void run() {
                onUpdateView();
            }
        });

    }

    protected abstract void onInflateView();

    /**
     * find view by id
     */
    protected abstract void onFindViewById();

    /**
     * refresh list view when message status change
     */
    protected void onUpdateView() {

        if (message.msg_send_status == MessageEntity.MsgSendStatus.SUCCESS.toNumber()) {
            LogUtil.d("message.msg_send_status == MessageEntity.MsgSendStatus.SUCCESS.toNumber()  ");
            progressBar.setVisibility(View.GONE);
            statusView.setVisibility(View.GONE);
            adapter.notifyDataSetChanged();
        } else {
            LogUtil.d("message.msg_send_status != MessageEntity.MsgSendStatus.SUCCESS.toNumber()  ");
            statusView.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);
        }
    }

    /**
     * setup view
     */
    protected abstract void onSetUpView();

    /**
     * on bubble clicked
     */
    protected abstract void onBubbleClick();

    /**
     * 构建发送的map
     */
    protected void buildSendMap() {
        sendMap = new HashMap<>();
        sendMap.put("user_id", userId);
        sendMap.put("msg_type", message.msg_content_type);
        LogUtil.d("message.msg_content_type     " + message.msg_content_type);
        if (message.msg_type == MsgType.CHAT_SINGLE.toNumber()) {
            sendMap.put("msg_recevier_id", localKeyId);
        } else if (message.msg_type == MsgType.CHAT_CROUP.toNumber()) {
            sendMap.put("group_id", localKeyId);
            sendMap.put("msg_org", ChatActivity.groupType);
        } else if (message.msg_type == MsgType.CHAT_QAC_FORM.toNumber()) {
            sendMap.put("form_id", message.form_id);
            sendMap.put("form_type", message.form_type);
            sendMap.put("receiver_id", localKeyId);
        }
        sendMap.put("msg_text", message.msg_content);
        if (ChatFileEntity.isNeedSaveFile(message.msg_content_type)) {
            message.msg_content = "";
        }
        LogUtil.d(sendMap.toString());
    }

    /**
     * 发送成功的处理
     */
    protected void commonSendSuccessDeal(BaseReturnBean bean) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(bean.data);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String msg_id = jsonObject.optString("msg_id");
        final String msg_time = jsonObject.optString("msg_time");
        //共同的发送回调
        LogUtil.d(TAG, "progressbar visibe" + (progressBar.getVisibility() == View.VISIBLE));
        LogUtil.d(TAG, "statusView visibe" + (statusView.getVisibility() == View.VISIBLE));
        message.msg_send_status = MessageEntity.MsgSendStatus.SUCCESS.toNumber();
        updateView();
        LogUtil.d(TAG, " 成功处理 ，开始修改状态");
        LogUtil.d(TAG, " 成功处理 ，开始修改状态，，更新消息列表状态");
        //发送成功的记录，如果列表不是此条对应的记录，则不需更新
//            MessageEntity msgEntity = MessageRecordDao.getInstance().getMessageEntityByKeyId(message.msg_sender_id);
        if (message.msg_type == MsgType.CHAT_SINGLE.toNumber()) {
            localKeyId = message.msg_sender_id;
        } else if (message.msg_type == MsgType.CHAT_CROUP.toNumber()) {
            localKeyId = message.msg_group_id;
        } else if (message.msg_type == MsgType.CHAT_QAC_FORM.toNumber()) {
            localKeyId = message.msg_sender_id;
        }
        //并且更新为最新时间
        if (message.msg_type != MsgType.CHAT_QAC_FORM.toNumber()) {
            registerSubscription(MessageRecordDao.getInstance().getiMessageData()
                    .updateMessageEntityStatus(localKeyId, MessageEntity.MsgSendStatus.SUCCESS.toNumber(), message.msg_type)
                    .subscribeOn(Schedulers.io())
                    .subscribe());
            registerSubscription(MessageRecordDao.getInstance().getiMessageData()
                    .updateMessageLastTime(localKeyId, msg_time, message.msg_type)
                    .subscribeOn(Schedulers.io())
                    .subscribe());
            //更新消息列表的最新发送状态
            registerSubscription(MessageRecordDao.getInstance().getiMessageData().getMessageEntityByKeyId(localKeyId, message.msg_type)
                            .subscribeOn(Schedulers.io())
                            .subscribe(new Action1<MessageEntity>() {
                                @Override
                                public void call(MessageEntity entity) {

                                    if (entity != null && message.msg_last_time != null && message.msg_last_time.equals(entity.msg_last_time)) {
                                        LogUtil.d(entity.msg_last_time);
                                        //对应是，更新状态
//                MessageRecordDao.getInstance().updateMessageEntityStatus(message.msg_sender_id, MessageEntity.MsgSendStatus.SUCCESS.toNumber());

                                    }
                                }
                            })
            );
        }


        LogUtil.d(TAG, " 成功处理 ，开始修改状态更新消息列表状态，，，更新消息记录状态");
        registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation()
                .updateMsgRecordSendStatus(message.inserttime, MessageEntity.MsgSendStatus.SUCCESS.toNumber())
                .subscribeOn(Schedulers.io())
                .subscribe());
        //更新消息记录状态
        registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation()
                .updateLastTime(message.inserttime, msg_time)
                .subscribeOn(Schedulers.io())
                .subscribe());

        message.msg_id = msg_id;
        message.msg_last_time = msg_time;
        LogUtil.d(TAG, " 成功处理 ，修改msg_id");
        registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation()
                .updateMsgRecordMsgId(message.inserttime, msg_id)
                .subscribeOn(Schedulers.io())
                .subscribe());
//        ChatRecordDao.getInstance().updateMsgRecordMsgId(message.inserttime, msg_id);
        if (ChatFileEntity.isNeedSaveFile(message.msg_content_type)) {
            LogUtil.d(TAG, " 成功处理 ，保存文件对象");
            String remote_url = jsonObject.optString("msg_text");
            message.mFileEntity.file_url_remote = remote_url;
            LogUtil.d(TAG, " 成功处理 ，保存文件对象 msgid");
//            ChatFileDao.getInstance().updateFileMsgIdPath(message.inserttime, message.msg_id);
            registerSubscription(ChatFileDao.getInstance().getiChatFileData().updateFileMsgIdPath(message.inserttime, message.msg_id)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe());

            LogUtil.d(TAG, " 成功处理 ，保存文件对象 服务器路径v");
            registerSubscription(ChatFileDao.getInstance().getiChatFileData().updateFileRemotePathByTime(message.inserttime, message.mFileEntity.file_url_remote)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe());
//            ChatFileDao.getInstance().updateFileRemotePathByTime(message.inserttime, message.mFileEntity.file_url_remote);

        }
    }

    /**
     * 发送失败的处理
     */
    protected void commonSendFailedDeal() {
        LogUtil.d(TAG, " 失败处理 ，开始修改状态");
        message.msg_send_status = MessageEntity.MsgSendStatus.FAILED.toNumber();
        updateView();
        //更新消息列表
//        MessageRecordDao.getInstance().updateMessageEntityStatus(message.msg_sender_id, MessageEntity.MsgSendStatus.FAILED.toNumber(), message.msg_type);
//        //更新消息记录
        registerSubscription(
                MessageRecordDao.getInstance().getiMessageData()
                        .updateMessageEntityStatus(localKeyId, MessageEntity.MsgSendStatus.FAILED.toNumber(), message.msg_type)
                        .subscribeOn(Schedulers.io())
                        .subscribe()
        );
        registerSubscription(ChatRecordDao.getInstance().getIChatRecordOperation()
                .updateMsgRecordSendStatus(message.inserttime, MessageEntity.MsgSendStatus.FAILED.toNumber())
                .subscribeOn(Schedulers.io())
                .subscribe());

//        ChatRecordDao.getInstance().updateMsgRecordSendStatus(message.inserttime, MessageEntity.MsgSendStatus.FAILED.toNumber());
    }

    /**
     * 发送后之前的准备
     */
    protected void commonSendBefore() {

    }

//    protected OkHttpManager.DataCallBack mCallback = new OkHttpManager.DataCallBack() {
//        @Override
//        public void requestBefore() {
//            commonSendBefore();
//        }
//
//        @Override
//        public void requestFailure(Request request, Exception e) {
//            //发送失败，更新UI
//            commonSendFailedDeal();
//        }
//
//        @Override
//        public void requestSuccess(BaseReturnBean result) throws Exception {
//            if (ErrorCode.SUCCESS_CODE_WNX.equals(result.code)) {
//                LogUtil.d(TAG, " 上传成功，回调 code" + result.code);
//                commonSendSuccessDeal(result);
//            } else {
//                commonSendFailedDeal();
//            }
//
//        }
//
//        @Override
//        public void requestSuccess(String result) throws Exception {
//            //文件下载使用
//        }
//    };


    /**
     * 通过http发送消息
     */
    protected void sendMessageByHttp() {
        LogUtil.d(TAG, "sendMessageByHttp");
        buildSendMap();
        LogUtil.d(TAG, "sendMap == null ?" + sendMap == null ? "true" : "false");
        String url = Constants.sendHXSingleChatMsg;
        if (message.msg_type == MsgType.CHAT_CROUP.toNumber()) {
            url = Constants.sendMultiChatMsg;
        } else if (message.msg_type == MsgType.CHAT_QAC_FORM.toNumber()) {
            url = Constants.SEND_FORM_CHAT;
        }
        //提交消息
//        OkHttpManager.postAsyncRX(url, sendMap, mCallback);
        OkHttpManager.getInstance().commonRequest(url, sendMap)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseReturnBean>() {
                    @Override
                    public void onCompleted() {
                        LogUtil.d(TAG, "wubaojie>>>onCompleted: 消息发送流程结束");
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        LogUtil.d(TAG, "wubaojie>>>onError: 消息发送失败:");
                        commonSendFailedDeal();
                    }

                    @Override
                    public void onNext(BaseReturnBean baseReturnBean) {
                        LogUtil.d(TAG, "wubaojie>>>onNext: 消息发送成功:" + baseReturnBean.data);
                        commonSendSuccessDeal(baseReturnBean);
                    }
                });
    }

    //    Subscriber<BaseReturnBean> chatSub = ;
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        clearSubscription();
    }

}
